package com.wisdytech.linkdcs.equipLifeCycle.malfunction.service.impl;

import com.wisdytech.linkdcs.equipLifeCycle.malfunction.model.MAttachment;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.DateUtil;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.dao.IMAttachmentDao;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.service.IMAttachmentService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dailibo
 * @since 2018-06-11
 */
@Service
@Transactional
public class MAttachmentServiceImpl extends BaseService<IMAttachmentDao, MAttachment> implements IMAttachmentService {

	private Logger logger =LoggerFactory.getLogger(getClass());
	
	@Autowired
	private IMAttachmentDao iMAttachmentDao;
	
	@Value("${img.localtion}")
    private String localtion;
	
	@Override
	public String saveFile(MultipartFile file) {
		
		if(!file.isEmpty()){
    	   String pathReal = localtion+"upload/malfunction";
//	           //文件位置存放在tomcat webapp根目录
           String fileName = file.getOriginalFilename();
           String [] fileNames =fileName.split("\\.");
           
           //filename
           String realName =DateUtil.getCurDateDefaultStr()+"/"+BaseUtil.getUUID()+"."+fileNames[1];
           
           File targetFile = new File(pathReal, realName);  

           if(!targetFile.getParentFile().exists()){
        	   targetFile.getParentFile().mkdirs();
           }
           
           try {  
               file.transferTo(targetFile);  
               return "upload/malfunction/"+realName;
           } catch (Exception e) {  
               e.printStackTrace(); 
               throw new ServiceException("保存故障附件失败");
           }
	    }
		return null;
	}

	@Override
	public boolean add(MAttachment attachment) {
		attachment.setPkId(BaseUtil.getUUID());
		return attachment.insert();
	}

	@Override
	public MAttachment getRecord(String recordId) {
		MAttachment ma =new MAttachment();
		ma.setRecordId(recordId);
		
		return iMAttachmentDao.selectOne(ma);
	}

}
